﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.Mappings;

namespace Apollo
{
    [NHibernateEntity(Table = "apl_MenuItems")]
    public class MenuItem
    {
        public MenuItem() { }

        [PrimaryKey]
        public virtual int Id { get; set; }

        [Property]
        public virtual string Name { get; set; }

        [Property]
        public virtual int DisplayOrder { get; set; }

        [Property]
        public virtual string IconPath { get; set; }

        [BelongsTo(Column = "ID_Parent_MenuItem")]
        public virtual MenuItem Parent { get; set; }

        [BelongsTo(Column = "ID_EntityView")]
        public virtual EntityView EntityView { get; set; }

        [Property]
        public virtual string NavigateUrl { get; set; }

        public bool IsAllowed() {
            IUser u = Apollo.Application.CurrentUser;

            if (u == null || u.Role == null)
                return false;

            if (u.Role.Name == Role.ADMIN_ROLE)
                return true;

            if (Apollo.Application.Meta<MenuItemAccess>().Any<MenuItemAccess>(mia => mia.MenuItem.Id == this.Id && mia.Enabled == true && mia.Role != null && mia.Role.Name == u.Role.Name))
                return true;

            if (u.Position != null && Apollo.Application.Meta<MenuItemAccess>().Any<MenuItemAccess>(mia => mia.MenuItem.Id == this.Id && mia.Enabled == true && mia.Position != null && mia.Position.Name == u.Position.Name))
                return true;

            return false;
        }
    }
}
